package com.heima.trade.listener;

import com.heima.api.client.PayClient;
import com.heima.api.dto.PayOrderVO;
import com.heima.trade.constant.MQConstant;
import com.heima.trade.domain.po.Order;
import com.heima.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author gonghuaiguo
 */
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    private final PayClient payClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MQConstant.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MQConstant.DELAY_ORDER_KEY
    ))
    public void listenerDelayMessage(Long orderId){
        // 1. 查询订单
        Order byId = orderService.getById(orderId);
        // 2. 检查订单状态，判断是否已支付
        if(byId == null || byId.getStatus() != 1){
            // 订单不存在或者已支付
            return;
        }
        // 3. 未支付，需要查询支付状态
        PayOrderVO payOrderVO = payClient.queryPayOrderByBizOrderNo(orderId);
        // 4. 判断是否支付
        if(payOrderVO!=null && payOrderVO.getStatus() == 3){
            // 4.1 已支付，修改订单状态
            orderService.markOrderPaySuccess(orderId);
        } else {
            // TODO 4.2 未支付，取消订单，恢复库存
            orderService.cancelOrder(orderId);
        }
    }

}
